<template>
  <vue-content>
    <vue-header>
      <vue-header-form>
        <el-form :inline="true" :model="formFilter" ref="formFilter">
          <el-form-item label="积分信息导入模板">
            <el-button size="small" type="info" @click="integraldownload">下载</el-button>
          </el-form-item>
          <el-form-item label="上传excel流">
            <el-upload
              class="upload-demo"
              :action="baseUrl()"
              :auto-upload = "false"
              :on-remove="handleRemove"
              :on-change="handleChange"
              accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
              :file-list="fileList">
              <el-button type="info">选择文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="info" @click="Submit('formFilter')">导入</el-button>
          </el-form-item>
        </el-form>
      </vue-header-form>
    </vue-header>
    <vue-body>
      <el-table
        v-loading.body="loading"
        :data="tableData"
        v-if="tableData != ''"
        border
        style="width: 100%">
        <el-table-column label="批量导入错误信息表">
        <el-table-column
          prop="name"
          width="150"
          label="员工姓名">
        </el-table-column>
        <el-table-column
          prop="staffNo"
          label="工号">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话" width="130">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="idNo"
          label="证件编号">
        </el-table-column>
        <el-table-column
          prop="errorReason"
          label="错误原因">
        </el-table-column>
        </el-table-column>
      </el-table>
      <el-table
        v-loading.body="loading"
        :data="rightTableData"
        v-if="rightTableData != ''"
        border
        style="width: 100%">
        <el-table-column label="已成功导入积分信息表">
        <el-table-column
          prop="name"
          width="150"
          label="员工姓名">
        </el-table-column>
        <el-table-column
          prop="staffNo"
          label="工号">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话" width="130">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="idNo"
          label="证件编号">
        </el-table-column>
        </el-table-column>
      </el-table>
    </vue-body>
    <vue-footer style="padding: 5px 0;margin: 0 -5px;float:right;">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="10"
        layout="total, prev, pager, next"
        :total="pageSize">
      </el-pagination>
    </vue-footer>
    <br/>
    <vue-header-button>
      <el-button type="info" @click="back()">后退</el-button>
      <el-button type="info" v-if="formFilter.applyNo != ''" @click="stopSubmit()">取消导入</el-button>
      <el-button type="info" v-if="formFilter.applyNo != ''" @click="finalySubmit()">提 交</el-button>
    </vue-header-button>
    <br/>
  </vue-content>
</template>
<script>
  import {confirmImportIntegral,queryImportIntegral,cancelImport} from '@/services/batchImport'
  import { oneFile } from "@/services/getFromData";
  import {queryStaffApply} from '@/services/batchImport'
  import {RequestError} from '@/services/errors'
  import {deepClone} from '@/utilities/object'
  export default {
    name: 'comp-table',
    components: {},
    data: () => ({
      loading: false,
      currentPage: 1,
      pageSize: 10,
      rightTableData:[],
      tableData: [],
      file:{},
			fileList:[],
      currentPage: 1,
      pageSize: 10,
      formFilter: {
        companyNo: "",
        applyNo:""
      },
      loading: false,
      view: '',
      applyNo:""
    }),
    created () {
      // 取到路由带过来的参数 
      let routerParams = this.$route.query;
      // 将数据放在当前组件的数据内
      this.formFilter.companyNo = routerParams.companyNo;
    },
    computed: {
    },
    methods: {
      async loadData () {
        this.loading = true
        try {
          let data = await queryImportIntegral(Object.assign({currentPage: this.currentPage},{perPage:10}, this.formFilter))
          // debugger
          this.rightTableData = data.data
          this.pageSize = parseInt(data.totalResult)
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
      },
      baseUrl(){
        return "";
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handleChange(file,fileList){
          if(fileList.length > 1){
            if(document.getElementsByClassName("el-upload-list__item")[0].firstChild.nodeName === 'IMG'){
              this.$message.warning('当前限制选择 1个文件,多个文件覆盖第一个');
              var thisNode = document.getElementsByClassName("el-upload-list__item")[1];
              thisNode.parentNode.removeChild(thisNode);
            }else{
              this.$message.warning('当前限制选择 1个文件,多个文件覆盖第一个');
              var thisNode = document.getElementsByClassName("el-upload-list__item")[0];
              thisNode.parentNode.removeChild(thisNode);
            }
          }
          var isEXL = ""
          if(file.raw.type === 'application/vnd.ms-excel' || file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
            isEXL = true
          }else{
            isEXL = false
          }
          const isLt10M = file.size / 1024 / 1024 < 10;
          if (!isEXL) {
            this.$message.error('只能上传Excel文档!');
          }
          if (!isLt10M) {
            this.$message.error('上传Excel文档大小不能超过 2MB!');
          }
          return isEXL && isLt10M;
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      download(){
        // 下载导入Excel模板
          window.open("https://codeload.github.com/douban/douban-client/legacy.zip/master");
      },
      integraldownload(){
        // 下载导入Excel模板
          window.open("https://codeload.github.com/douban/douban-client/legacy.zip/master");
      },
      back(){
        this.$router.go(-1)
      },
      Submit(formName) {
        this.Subabled = true;
        this.butTimeOut();
        this.$refs[formName].validate(async valid => {
          if (valid) {
            try {
                var sref = this;
                //把图片的信息和参数放进请求头里
                let code = await oneFile({
                  companyNo:this.formFilter.companyNo
                },"/ecshop/staff/resolveStaffAccountExcelTemplate.do","file").then(
                  function(data){
                    sref.$message({
                      showClose: true,
                      message: "导入成功",
                      type: "success"
                    });
                    // console.log(data)
                    sref.tableData = data.data.errorList
                    sref.applyNo = data.data.applyNo;
                    sref.formFilter.applyNo = data.data.applyNo;
                    sref.loadData();
                  }, 
                  function(reason, data){
                    sref.$message({
                      showClose: true,
                      message: reason,
                      type: "error"
                    });
                  });
            } catch (e) {
              if (e instanceof RequestError) {
                this.$alert(e.message, "提示", {
                  type: "error",
                  confirmButtonText: "确定"
                });
              } else {
                throw e;
              }
            }
          } else {
            return;
          }
        });
      },
      async finalySubmit(){
        this.Subabled = true;
        this.butTimeOut();
        try {
          await confirmImportStaff(this.formFilter.applyNo);
          this.$emit("close", true);
          this.$message({
            showClose: true,
            message: "提交成功",
            type: "success"
          });
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, "提示", {
              type: "error",
              confirmButtonText: "确定"
            });
          } else {
            throw e;
          }
        }
      },
      async stopSubmit(){
        this.Subabled = true;
        this.butTimeOut();
        try {
          await cancelImport(this.formFilter.applyNo,this.formFilter.companyNo);
          this.$emit("close", true);
          this.$message({
            showClose: true,
            message: "已取消积分信息导入",
            type: "success"
          });
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, "提示", {
              type: "error",
              confirmButtonText: "确定"
            });
          } else {
            throw e;
          }
        }
      },
      butTimeOut(){
        var serf = this;
        setTimeout(function(){
          serf.Subabled = false;
        },1200)
      }
    },
    watch: {
      currentPage (newVal) {
        this.loadData(newVal)
      }
    },
    filters: {
      applyStatus (value) {
        return {"00": '删除',"01": '草稿', "02": '已提交', "03": '已审核', "04": '拒绝', "05": '已完成', "06": '已取消'}[value]
      }
    },
  }
</script>

<style>
	.logoImgPic{
		height: 100px;
		display: block;
	}
	.el-table th>.cell{
		text-align: center;
	}
</style>
